<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测评记录</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .record-card {
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
            background: #fff;
        }
        
        .record-card:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .record-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px;
            border-radius: 8px 8px 0 0;
        }
        
        .record-body {
            padding: 20px;
        }
        
        .score-display {
            font-size: 2rem;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }
        
        .status-completed {
            background-color: #d4edda;
            color: #155724;
        }
        
        .status-in-progress {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .status-not-started {
            background-color: #f8d7da;
            color: #721c24;
        }
        
        .progress-bar-custom {
            height: 8px;
            border-radius: 4px;
        }
        
        .info-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .info-item:last-child {
            border-bottom: none;
        }
        
        .info-label {
            font-weight: 500;
            color: #666;
        }
        
        .info-value {
            color: #333;
        }
        
        .action-buttons {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #f0f0f0;
        }
        
        .btn-custom {
            margin-right: 10px;
            border-radius: 20px;
            padding: 8px 20px;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }
        
        .empty-state i {
            font-size: 4rem;
            color: #ddd;
            margin-bottom: 20px;
        }
        
        .loading-spinner {
            text-align: center;
            padding: 40px;
        }
        
        .filter-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .scale-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container-fluid py-4">
        <!-- 返回按钮 -->
        <div class="mb-3">
            <button class="btn btn-outline-secondary" onclick="goBack()">
                <i class="fas fa-arrow-left me-2"></i>返回量表选择
            </button>
        </div>
        
        <!-- 量表信息 -->
        <div class="scale-info" id="scale-info" style="display: none;">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h4 class="mb-1" id="scale-title">量表名称</h4>
                    <p class="mb-0" id="scale-description">量表描述</p>
                </div>
                <div class="col-md-4 text-end">
                    <div class="d-flex justify-content-end align-items-center">
                        <div class="me-3">
                            <small>题目数量</small>
                            <div class="h5 mb-0" id="scale-questions">0</div>
                        </div>
                        <div>
                            <small>预计时间</small>
                            <div class="h5 mb-0" id="scale-duration">0分钟</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 筛选和排序 -->
        <div class="filter-section">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <div class="d-flex align-items-center">
                        <label class="form-label me-3 mb-0">状态筛选:</label>
                        <select class="form-select" id="status-filter" style="width: auto;">
                            <option value="">全部状态</option>
                            <option value="completed">已完成</option>
                            <option value="in_progress">进行中</option>
                            <option value="not_started">未开始</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="d-flex align-items-center justify-content-end">
                        <label class="form-label me-3 mb-0">排序:</label>
                        <select class="form-select" id="sort-select" style="width: auto;">
                            <option value="created_at_desc">创建时间(新到旧)</option>
                            <option value="created_at_asc">创建时间(旧到新)</option>
                            <option value="score_desc">分数(高到低)</option>
                            <option value="score_asc">分数(低到高)</option>
                            <option value="status">状态</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 加载状态 -->
        <div class="loading-spinner" id="loading-spinner">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2">正在加载测评记录...</p>
        </div>
        
        <!-- 记录列表 -->
        <div id="records-container" style="display: none;">
            <!-- 记录将在这里动态生成 -->
        </div>
        
        <!-- 空状态 -->
        <div class="empty-state" id="empty-state" style="display: none;">
            <i class="fas fa-clipboard-list"></i>
            <h5>暂无测评记录</h5>
            <p>您还没有进行过此量表的测评，请先完成测评。</p>
        </div>
        
        <!-- 分页 -->
        <nav aria-label="记录分页" id="pagination-container" style="display: none;">
            <ul class="pagination justify-content-center" id="pagination">
                <!-- 分页将在这里动态生成 -->
            </ul>
        </nav>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let currentScaleId = null;
        let currentPage = 1;
        let totalPages = 1;
        let allRecords = [];
        let filteredRecords = [];
        
        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            // 从URL参数获取量表ID
            const urlParams = new URLSearchParams(window.location.search);
            const scaleId = urlParams.get('scale_id');
            
            if (scaleId) {
                currentScaleId = scaleId;
                loadScaleInfo(scaleId);
                loadRecords(scaleId);
            } else {
                showError('未指定量表ID');
            }
            
            // 绑定事件
            document.getElementById('status-filter').addEventListener('change', filterRecords);
            document.getElementById('sort-select').addEventListener('change', sortAndRenderRecords);
        });
        
        // 加载量表信息
        async function loadScaleInfo(scaleId) {
            try {
                const response = await fetch(`/api/scales/${scaleId}`);
                if (response.ok) {
                    const scale = await response.json();
                    displayScaleInfo(scale);
                } else {
                    console.error('加载量表信息失败:', response.status);
                }
            } catch (error) {
                console.error('加载量表信息出错:', error);
            }
        }
        
        // 显示量表信息
        function displayScaleInfo(scale) {
            document.getElementById('scale-title').textContent = scale.title;
            document.getElementById('scale-description').textContent = scale.description || '暂无描述';
            document.getElementById('scale-questions').textContent = scale.question_count || 0;
            document.getElementById('scale-duration').textContent = scale.estimated_duration || 0;
            document.getElementById('scale-info').style.display = 'block';
        }
        
        // 加载测评记录
        async function loadRecords(scaleId) {
            try {
                showLoading(true);
                console.log('开始加载量表记录, scaleId:', scaleId);
                
                const response = await fetch(`/api/scales/${scaleId}/assessments`);
                console.log('API响应状态:', response.status);
                
                if (response.ok) {
                    const data = await response.json();
                    console.log('获取到的记录数据:', data);
                    
                    allRecords = data.assessments || [];
                    console.log('记录数量:', allRecords.length);
                    
                    filterRecords();
                } else {
                    const errorData = await response.json();
                    console.error('加载记录失败:', errorData);
                    showError('加载测评记录失败: ' + (errorData.message || '未知错误'));
                }
            } catch (error) {
                console.error('加载记录出错:', error);
                showError('网络错误，请稍后重试');
            } finally {
                showLoading(false);
            }
        }
        
        // 筛选记录
        function filterRecords() {
            const statusFilter = document.getElementById('status-filter').value;
            
            if (statusFilter) {
                filteredRecords = allRecords.filter(record => record.status === statusFilter);
            } else {
                filteredRecords = [...allRecords];
            }
            
            console.log('筛选后的记录数量:', filteredRecords.length);
            sortAndRenderRecords();
        }
        
        // 排序并渲染记录
        function sortAndRenderRecords() {
            const sortBy = document.getElementById('sort-select').value;
            
            // 排序逻辑
            switch (sortBy) {
                case 'created_at_desc':
                    filteredRecords.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
                    break;
                case 'created_at_asc':
                    filteredRecords.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
                    break;
                case 'score_desc':
                    filteredRecords.sort((a, b) => (b.total_score || 0) - (a.total_score || 0));
                    break;
                case 'score_asc':
                    filteredRecords.sort((a, b) => (a.total_score || 0) - (b.total_score || 0));
                    break;
                case 'status':
                    filteredRecords.sort((a, b) => a.status.localeCompare(b.status));
                    break;
            }
            
            renderRecords();
        }
        
        // 渲染记录列表
        function renderRecords() {
            const container = document.getElementById('records-container');
            const emptyState = document.getElementById('empty-state');
            
            if (filteredRecords.length === 0) {
                container.style.display = 'none';
                emptyState.style.display = 'block';
                return;
            }
            
            emptyState.style.display = 'none';
            container.style.display = 'block';
            
            let html = '';
            
            filteredRecords.forEach(record => {
                html += generateRecordCard(record);
            });
            
            container.innerHTML = html;
            console.log('记录渲染完成，生成HTML长度:', html.length);
        }
        
        // 生成单个记录卡片
        function generateRecordCard(record) {
            const statusText = getStatusText(record.status);
            const statusClass = getStatusBadgeClass(record.status);
            const progress = getProgress(record);
            const duration = getDuration(record);
            
            return `
                <div class="record-card">
                    <div class="record-header">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <h6 class="mb-1">测评记录 #${record.id}</h6>
                                <small>创建时间: ${formatDateTime(record.created_at)}</small>
                            </div>
                            <div class="col-md-4 text-end">
                                <span class="status-badge ${statusClass}">${statusText}</span>
                            </div>
                        </div>
                    </div>
                    <div class="record-body">
                        <div class="row">
                            <div class="col-md-3 text-center">
                                <div class="score-display">${record.total_score || '--'}</div>
                                <small class="text-muted">总分</small>
                            </div>
                            <div class="col-md-9">
                                <div class="info-item">
                                    <span class="info-label">完成进度:</span>
                                    <div class="d-flex align-items-center">
                                        <div class="progress me-2" style="width: 100px; height: 8px;">
                                            <div class="progress-bar bg-primary" style="width: ${progress}%"></div>
                                        </div>
                                        <span class="info-value">${progress}%</span>
                                    </div>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">用时:</span>
                                    <span class="info-value">${duration}</span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">完成时间:</span>
                                    <span class="info-value">${record.completed_at ? formatDateTime(record.completed_at) : '未完成'}</span>
                                </div>
                                ${record.risk_level ? `
                                <div class="info-item">
                                    <span class="info-label">风险等级:</span>
                                    <span class="info-value">${getRiskText(record.risk_level)}</span>
                                </div>
                                ` : ''}
                            </div>
                        </div>
                        <div class="action-buttons">
                            <button class="btn btn-primary btn-sm btn-custom" onclick="viewDetail(${record.id})">
                                <i class="fas fa-eye me-1"></i>查看详情
                            </button>
                            ${record.status === 'completed' ? `
                            <button class="btn btn-success btn-sm btn-custom" onclick="downloadReport(${record.id})">
                                <i class="fas fa-download me-1"></i>下载报告
                            </button>
                            ` : ''}
                            ${record.status === 'in_progress' ? `
                            <button class="btn btn-warning btn-sm btn-custom" onclick="continueAssessment(${record.id})">
                                <i class="fas fa-play me-1"></i>继续测评
                            </button>
                            ` : ''}
                        </div>
                    </div>
                </div>
            `;
        }
        
        // 工具函数
        function getStatusText(status) {
            const statusMap = {
                'completed': '已完成',
                'in_progress': '进行中',
                'not_started': '未开始'
            };
            return statusMap[status] || status;
        }
        
        function getStatusBadgeClass(status) {
            const classMap = {
                'completed': 'status-completed',
                'in_progress': 'status-in-progress',
                'not_started': 'status-not-started'
            };
            return classMap[status] || 'status-not-started';
        }
        
        function getProgress(record) {
            if (record.status === 'completed') return 100;
            if (record.status === 'not_started') return 0;
            return record.progress || 0;
        }
        
        function getDuration(record) {
            if (record.duration) {
                const minutes = Math.floor(record.duration / 60);
                const seconds = record.duration % 60;
                return `${minutes}分${seconds}秒`;
            }
            return '未知';
        }
        
        function getRiskText(riskLevel) {
            const riskMap = {
                'low': '低风险',
                'medium': '中风险',
                'high': '高风险'
            };
            return riskMap[riskLevel] || riskLevel;
        }
        
        function formatDateTime(dateString) {
            if (!dateString) return '未知';
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }
        
        // 操作函数
        function viewDetail(recordId) {
            console.log('查看详情, recordId:', recordId);
            window.open(`/assessments/${recordId}/results`, '_blank');
        }
        
        function downloadReport(recordId) {
            console.log('下载报告, recordId:', recordId);
            window.open(`/api/assessments/${recordId}/report`, '_blank');
        }
        
        function continueAssessment(recordId) {
            console.log('继续测评, recordId:', recordId);
            window.location.href = `/assessments/${recordId}/continue`;
        }
        
        // 显示/隐藏加载状态
        function showLoading(show) {
            const spinner = document.getElementById('loading-spinner');
            const container = document.getElementById('records-container');
            const emptyState = document.getElementById('empty-state');
            
            if (show) {
                spinner.style.display = 'block';
                container.style.display = 'none';
                emptyState.style.display = 'none';
            } else {
                spinner.style.display = 'none';
            }
        }
        
        // 显示错误信息
        function showError(message) {
            alert('错误: ' + message);
        }
        
        // 返回量表选择页面
        function goBack() {
            window.location.href = '/members/records';
        }
    </script>
</body>
</html>